package com.fan.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fan.reggie.common.BaseContext;
import com.fan.reggie.common.R;
import com.fan.reggie.dto.OrdersDto;
import com.fan.reggie.entity.Dish;
import com.fan.reggie.entity.OrderDetail;
import com.fan.reggie.entity.Orders;
import com.fan.reggie.service.OrderDetailService;
import com.fan.reggie.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;


    /*用户下单
    * */
    @PostMapping("/submit")
    public R<String> sumbit(@RequestBody Orders orders){
        log.info("用户下单中...");
        ordersService.submit(orders);
        return R.success("下单成功！！");
    }

    /**用户（历史）订单查询
     * */
    @GetMapping("/userPage")
    public R<Page> page(int page, int pageSize){
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        Long currentId = BaseContext.getCurrentId();

        queryWrapper.eq(currentId!=null, Orders::getUserId, currentId);
        queryWrapper.orderByDesc(Orders::getOrderTime);
        Page<Orders> ordersPage = ordersService.page(pageInfo, queryWrapper);

        //数据拷贝
        List<OrdersDto> list = ordersPage.getRecords().stream().map((item->{
            OrdersDto ordersDto = new OrdersDto();
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            BeanUtils.copyProperties(item, ordersDto);
            orderDetailLambdaQueryWrapper.eq(item.getNumber()!=null, OrderDetail::getOrderId, item.getId());
            List<OrderDetail> orderDetails = orderDetailService.list(orderDetailLambdaQueryWrapper);
            ordersDto.setOrderDetails(orderDetails);
            return ordersDto;
        })).collect(Collectors.toList());
        ordersDtoPage.setRecords(list);
        return R.success(ordersDtoPage);
    }
}
